//
//  HMSportMapViewController.m
//  XRSport
//
//  Created by acer on 16/10/21.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HMSportMapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "HMSportTrackingLine.h"
#import "HMSportPolyline.h"
#import "HMCircleAnimator.h"
#import "HMSportMapModelViewController.h"
//#import "NSObject+CZRuntime.h"
@interface HMSportMapViewController ()<MAMapViewDelegate,UIPopoverPresentationControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *distance;
@property (weak, nonatomic) IBOutlet UILabel *sportTimes;

@end

@implementation HMSportMapViewController
{
    //用户位置////////////////////
//    CLLocation *_startLocation;
//CAShapeLayer动画
    HMCircleAnimator *_animator;
    /// 是否设置了起始大头针
    BOOL _hasSetStartLocation;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
- (IBAction)closeMapBtnClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if (![segue.destinationViewController isKindOfClass:[HMSportMapModelViewController class]]) {
        return;
    }
//    NSLog(@"%@",segue.destinationViewController);
    HMSportMapModelViewController *vc = segue.destinationViewController;
    vc.popoverPresentationController.delegate = self;
    //宽度设置为0，则宽度系统会自己设置
    vc.preferredContentSize = CGSizeMake(0, 120);
    [vc setDidSelectedMapModel:^(MAMapType type) {
        self.mapView.mapType = type;
    }];
    vc.currentType = self.mapView.mapType;
    
}

//代理方法
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}


-(void)updateSportTimesAndDistance
{
    self.distance.text = [NSString stringWithFormat:@"%.02f", self.sportTracking.totalDistance];
    self.sportTimes.text = self.sportTracking.totalTimeStr;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        _animator = [HMCircleAnimator new];
        self.transitioningDelegate = _animator;
    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self setupMapView];
}
- (void)setupMapView
{
    ///初始化地图
    MAMapView *mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    
    ///把地图添加至view
    [self.view insertSubview:mapView atIndex:0];
    // 3. 隐藏比例尺
    mapView.showsScale = NO;
    // 4. 关闭相机旋转 - 能够降低能耗，省电
    mapView.rotateCameraEnabled = NO;
    // 5. 显示用户的位置
    mapView.showsUserLocation = YES;
    // 6. 跟踪用户的位置 - 可以将用户定位在地图的中心，并且放大地图，有的时候，速度会有些慢！
    mapView.userTrackingMode = MAUserTrackingModeFollow;
    // 7. 允许后台定位 - 保证 Background Modes 中的 Location updates 处于选中状态
    mapView.allowsBackgroundLocationUpdates = YES;
    // 8. 不允许系统暂停位置更新
    mapView.pausesLocationUpdatesAutomatically = NO;
    // 9. 设置代理
    mapView.delegate = self;
    
    _mapView = mapView;
}

#pragma mark - MAMapViewDelegate
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation) {
        return;
    }
    if (_sportTracking.sportState != HMSportStateContinue) {
        return;
    }
//    NSLog(@"%@",userLocation);
    
    //绘制轨迹
    [mapView addOverlay:[_sportTracking appendLocation:userLocation.location]];
    if (_hasSetStartLocation == NO && _sportTracking.startSportLocation != nil) {
        _hasSetStartLocation = YES;
//        _startLocation = userLocation.location;
        // 1. 实例化大头针
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        // 2. 指定坐标位置
        annotation.coordinate = _sportTracking.startSportLocation.coordinate;
        // 3. 添加到地图视图
        [mapView addAnnotation:annotation];
    }
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    [self updateSportTimesAndDistance];
    
    [self.delegate sportMapDataChanged:self];
}
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if (![annotation isKindOfClass:[MAPointAnnotation class]]) {
        return nil;
    }
    static NSString *annotationID = @"annotationID";
    MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:annotationID];
    if (annotationView == nil) {
        annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationID];
    }
    UIImage *img = _sportTracking.sportImage;
    annotationView.image = img;
    annotationView.centerOffset = CGPointMake(0, -img.size.height * 0.5);
    return annotationView;
}
//-(void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate
//{
//    CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
//    HMSportTrackingLine *trackingLine = [[HMSportTrackingLine alloc]initWithStartP:_startLocation endP:endLocation];
//    [mapView addOverlay:trackingLine.polyline];
//    [self dismissViewControllerAnimated:YES completion:nil];

//}
-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        HMSportPolyline *polyline = (HMSportPolyline *)overlay;
        MAPolylineRenderer *polylineView = [[MAPolylineRenderer alloc] initWithPolyline:polyline];
        
        polylineView.lineWidth = 10.f;
        polylineView.strokeColor = polyline.color;
        polylineView.lineJoinType = kMALineJoinRound;//连接类型
        polylineView.lineCapType = kMALineCapRound;//端点类型
        
        return polylineView;
    }
    return nil;
}
@end
